package ca.cbc.msb.console.bean;

import java.io.Serializable;
import javax.annotation.PostConstruct;
import javax.faces.event.ActionEvent;
import javax.inject.Inject;

import org.primefaces.model.TreeNode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import ca.cbc.medialib.entity.Category;
import ca.cbc.msb.console.transaction.CategoryTransaction;
import ca.cbc.msb.console.util.FacesMessageUtil;

@Controller
@Scope("session")
public class CategoryBean implements Serializable {
	private static final long serialVersionUID = -4406972699026543179L;
	protected Logger logger = LoggerFactory.getLogger(this.getClass());
	@Inject
	private CategoryTransaction categoryTransaction;
	private TreeNode root;
	private Category selected;
	
	private void sync() {
		root = categoryTransaction.getTreeNode();
	}
	
//	public void update() {
//		sync();
//		FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Updated", "Category tree has just been updated!"));
//	}
	
	@PostConstruct
	public void init() {
		logger.debug("^^^^^^^^^^^^^CategoryBean PostConstruct!");
		sync();
	}
	
    public void delete(ActionEvent actionEvent) { 
    	if(categoryTransaction.remove(selected.getId())) {
    		FacesMessageUtil.instance.addMessage("Successful", "Category " + selected.getFullTitle() + " deleted!");
    		sync();
    	} else {
    		FacesMessageUtil.instance.addMessage("Failed", "Category " + selected.getFullTitle() + " still have children/medias or already been deleted by msb!");
    	}   	
    	selected = null;
    }

    public void cancel(ActionEvent actionEvent) {
    	FacesMessageUtil.instance.addMessage("Canceled", "Delete canceled!");
    	selected = null;
    }
    
	public TreeNode getRoot() {
		return root;
	}
	
	public Category getSelected() {
		return selected;
	}
	
	public void setSelected(Category selected) {
		logger.debug("Set Selected Category ({})", selected);
		this.selected = categoryTransaction.load(selected.getId());
	}
}
